Repository navigation
fix: Prevent close from failing or hanging when called from a listener - #581
Conversation
… listener Listeners run on a data system thread, and stopping the FDv2 data system joined every one of its threads, including that one. The join raised, so the data store and big segment store were left open.
…stener A flag change listener called by an override update held the override sink lock, and close waited for that lock forever. Listeners are now notified after the lock is released. The FDv1 file data source with watchdog called listeners on the observer thread, and stop joined that thread. Stop now skips the join on that thread. A close from a listener during Store.apply let apply write the change set to the closed persistent store. The store now stops persisting after close.
There was a problem hiding this comment.
Risk: medium.
Automated risk review (dry run): Medium
This PR would not be automatically approved. Human approval required.
Why: This changes core client close/stop behavior across FDv2 thread join, the file data source observer thread, override-sink lock ordering, and persistent-store writes after close. Those interacting lifecycle paths are bounded by tests, but they are not a narrow low-risk change.
If you disagree with this review, share this PR in #feedback-agent-approvals or submit a changes-requested review explaining why.
Human review is needed and no reviewers were assigned.
Sent by Cursor Approval Agent: Dry-Run PR Approver
Deadlock: closing the client from a listener while an override snapshot is being appliedThis PR fixes the hang when an override listener closes the client. A related hang remains: a listener that fires on a LaunchDarkly update closes the client while the override source is applying a snapshot. Two threads take the store lock and the override sink lock in opposite order. The base commit has the same lock order, so this PR does not introduce it. But it is a listener thread on which close still does not work.
Impact: When it happens: all three of these at once:
The window is about one snapshot computation, which reads all flags and segments twice, so it grows with the size of the environment. It is rare, but when it happens the client hangs. Reproduction (forces the timing with a sleep)Run with the path to a checkout of this branch as the first argument. import sys, time, threading
sys.path.insert(0, sys.argv[1])
from ldclient import Context, datasystem
from ldclient.client import Config, LDClient
from ldclient.integrations.test_datav2 import TestDataV2
class Src:
def start(self, sink):
self.sink = sink
def close(self):
pass
class Builder:
def __init__(self): self.src = Src()
def build(self, config): return self.src
b = Builder()
td = TestDataV2.data_source()
td.update(td.flag('flag').on(True))
cfg = datasystem.custom().synchronizers(td.builder).overrides(b).build()
client = LDClient(Config('SDK_KEY', send_events=False, datasystem_config=cfg), start_wait=5)
assert client.is_initialized()
done = threading.Event()
def override_writer():
b.src.sink.set_overrides({'other': {'key': 'other', 'version': 1, 'on': True, 'variations': [True], 'fallthrough': {'variation': 0}}}, {})
def listener(change):
if change.key != 'flag' or done.is_set():
return
# The override source supplies a snapshot at this moment.
threading.Thread(target=override_writer, daemon=True).start()
time.sleep(0.3)
client.close()
done.set()
client.flag_tracker.add_listener(listener)
threading.Thread(target=lambda: td.update(td.flag('flag').on(False)), daemon=True).start()
print('close returned:', done.wait(4))
res = []
ev = threading.Thread(target=lambda: res.append(client.variation('flag', Context.create('u'), 'default')), daemon=True)
ev.start(); ev.join(3)
print('evaluation on another thread returned:', not ev.is_alive(), res)On d17de3d, 3 of 3 runs print Proposed fixMake @@ -49,11 +49,12 @@
self._notify = notify
self._has_listeners = has_listeners
self._lock = threading.Lock()
- self._closed = False # guarded by _lock
+ # An event, not a flag guarded by _lock, so close never waits for _lock.
+ self._closed = threading.Event()
def set_overrides(self, flags: Dict[str, Any], segments: Dict[str, Any]) -> None: # type: ignore[override]
with self._lock:
- if self._closed:
+ if self._closed.is_set():
log.debug("Ignoring an override snapshot supplied after the override source was closed")
return
try:
@@ -70,8 +71,9 @@
Stops accepting snapshots. Used when the client is closed: a snapshot that the source
supplies while it shuts down is ignored. The layer keeps its contents.
"""
- with self._lock:
- self._closed = True
+ # Does not take _lock. A listener can close the client while another thread holds
+ # _lock and waits for the store lock that the listener's thread holds.
+ self._closed.set()
def close_and_clear(self) -> None:
"""
@@ -80,7 +82,7 @@
overrides, and a late snapshot from the closed source is ignored.
"""
with self._lock:
- self._closed = True
+ self._closed.set()
affected = self._apply({}, {})
self._notify_all(affected)Trade-off: Alternative: Verified: I applied the patch to d17de3d. With it, the reproduction returns from |
# Conflicts: # ldclient/testing/impl/datasystem/test_fdv2_datasystem.py
Stop now sets the status to OFF. When a flag change listener closes the client, the synchronizer thread returned from the store apply and set the status of that update over OFF. The synchronizer loop now checks for stop after the apply.
…ing an override update A listener that closes the client runs while the store lock is held. If the override source applied a snapshot at the same time, that thread held the sink lock and waited for the store lock, and close waited for the sink lock. The sink close no longer takes the sink lock. A snapshot that is already in progress completes, and later snapshots are ignored.
|
Thanks, confirmed. Your reproduction hung on the branch after merging main. I applied your proposed fix as written in 52cb4dc: The merge with main also exposed a separate problem. #584 made |
There was a problem hiding this comment.
Risk: medium. SDK rules 1–3 pass (not a release PR, allowed author, no disallowed workflow changes), but the approval threshold is low only, so this is not approved. Cursor Bugbot completed with no findings; human review is needed and no reviewers were assigned.
Sent by Cursor Approval Agent: SDK - Pull Request Router and Approver


Summary
Closing the client from inside a listener now works on every thread the SDK calls listeners on.
Note
Overview
Makes
client.close()/stop()safe when invoked from flag-change, data-store, or file-reload listener threads.FDv2 skips
join()on the current thread during shutdown and bails out of in-flight synchronizer handling once stop is set so status is not flipped back from OFF. The Store tracks_closedand blocks further persistence to the backing feature store. OverrideSinkImpl uses a close Event (no lock on close), applies layer updates under the lock, and notifies listeners only after the lock is released. The file data source watchdog path skips joining the observer when stop runs on that same thread.New tests cover stopping FDv2 from a flag listener, closing the sink from a notify callback, close vs in-progress snapshots, file auto-update close paths, and full client close from flag/data-store listeners.
Reviewed by Cursor Bugbot for commit 52cb4dc. Bugbot is set up for automated code reviews on this repo. Configure here.